<template>
  <div class="upload-form">
    <el-form>
      <el-form-item label="图片上传">
        <el-upload
          ref="upload"
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-change="handleUploadChange"
          :auto-upload="false"
        >

          <div class="image-container">
            <el-image
              v-if="imageUrl"
              :src="imageUrl"
              :zoom-rate="1.0"
              fit="cover"
              style="width: 100%;height: 100%;object-fit: cover;display: block;"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" style="padding: 20px;" />

            <div v-if="imageUrl" class="image-overlay">
              <i class="el-icon-edit" />
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="图片预览">
        <el-image :src="imageUrl" style="max-width: 200px;" />
      </el-form-item>
      <el-button type="primary" size="medium" @click="uploadImage">上传图片</el-button>

    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '',
      uploadUrl: 'https://braincognitiontec.top:30005/static-file/upload-img'
    }
  },
  methods: {
    beforeUpload(file) {
      const suffix = file.name.lastIndexOf('.')
      const fileName = file.name.substring(0, suffix)
      console.log(suffix)
      console.log(fileName)

      return true
    },
    handlePreview(res) {
      console.log('res')
    },
    handleUploadChange(file, fileList) {
      console.log('jjj')
      file = file.raw
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return false
      }
      const suffix = file.name.lastIndexOf('.')
      const fileName = file.name.substring(0, suffix)
      console.log(file.name.substring(suffix))
      console.log(fileName)
      const url = URL.createObjectURL(file)
      console.log(url)
      this.imageUrl = url
    },
    handleSuccess(response) {
      console.log(response)
      if (response.data.success === false) {
        console.log(response.data.errorMsg)
      }
      this.imageUrl = response.data.fileUrl
    },
    uploadImage() {
      this.$refs.upload.submit()
    }
  }
}
</script>
